﻿using System;
using System.Data;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections.Generic;
using System.Linq;

namespace HRM
{
    public partial class frmUserList : DockContent
    {
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        bool _loadedData = false;
        UserClient _wcfUser;
        BranchClient _wcfBranch;
        string _BranchRegionCode = "";
        int _BranchID = 0;

        public frmUserList()
        {
            InitializeComponent();
            LoadLanguage();
            _wcfUser = Service.User();
            _wcfBranch = Service.Branch();

            BuildVoucherGrid();
            UISetting.LoadRegion(ref cboRegion);

            LoadUserList();
            btnNew.Enabled = btnEdit.Enabled = btnDel.Enabled = Program.isAdmin;
            pager.AllowChangePageSize = true;
            cboBranch2.SuggestComboBoxControl.SelectedIndexChanged += new EventHandler(SuggestComboBoxControl_SelectedIndexChanged);
        }

        void SuggestComboBoxControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            _BranchID = Convert.ToInt32(cboBranch2.SuggestComboBoxControl.SelectedValue);
            LoadUserList();
        }

        private void LoadLanguage()
        {
            if (this.Tag != null)
                this.TabText = this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }

        private void BuildVoucherGrid()
        {
            UISetting.AddColumn(ref dgvUserList, "UserName", UpdateUI.GetString("tennguoidung"), "", 150, true, true);
            UISetting.AddColumn(ref dgvUserList, "FullName", UpdateUI.GetString("hovaten"), "", 180, true, true);
            UISetting.AddColumn(ref dgvUserList, "BranchName", "Đơn vị", "", 180, true, true);
            UISetting.AddColumn(ref dgvUserList, "Phone", UpdateUI.GetString("dienthoai"), "", 100, true, true);
            UISetting.AddColumn(ref dgvUserList, "Address", UpdateUI.GetString("diachi"), "", 250, true, true);
            UISetting.AddColumn(ref dgvUserList, "Email", "Email", "", 250, true, true);
        }

        private void LoadUserList()
        {
            _wcfUser = Service.User();
            DataSet _ds;
            if (!Program.isAdmin && !Program.isViewAll && Program.strUserName.ToUpper() != "VVTUY")
            {
                _ds = _wcfUser.User_GetList(out itemCount, pager.PageIndex, pager.PageSize, _BranchRegionCode, Program.intBranchID);
            }
            else
                _ds = _wcfUser.User_GetList(out itemCount, pager.PageIndex, pager.PageSize, _BranchRegionCode, _BranchID);

            pager.TotalRow = itemCount;

            dgvUserList.Rows.Clear();

            for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
            {
                if (_ds.Tables[0].Rows[i]["UserName"].ToString().ToUpper() != "ADMIN")
                {
                    dgvUserList.Rows.Insert(i, 1);
                    dgvUserList.Rows[i].Cells["UserName"].Value = _ds.Tables[0].Rows[i]["UserName"].ToString();
                    dgvUserList.Rows[i].Cells["FullName"].Value = _ds.Tables[0].Rows[i]["FullName"].ToString();
                    dgvUserList.Rows[i].Cells["BranchName"].Value = _ds.Tables[0].Rows[i]["BranchName"].ToString();
                    dgvUserList.Rows[i].Cells["Phone"].Value = _ds.Tables[0].Rows[i]["Phone"].ToString();
                    dgvUserList.Rows[i].Cells["Address"].Value = _ds.Tables[0].Rows[i]["Address"].ToString();
                    dgvUserList.Rows[i].Cells["Email"].Value = _ds.Tables[0].Rows[i]["Email"].ToString();
                }
            }
            _loadedData = true;
        }


        private void cboBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (_loadedData)
            //{
            _BranchID = Convert.ToInt32(cboBranch2.SuggestComboBoxControl.SelectedValue);
            LoadUserList();
            //}
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvUserList.SelectedRows.Count > 0)
            {
                string userName = dgvUserList.SelectedRows[0].Cells["Username"].Value.ToString();
                Form f = new frmUserInfo(userName, new string[] { "", "", "", "0" });
                if (f.ShowDialog(this) == DialogResult.OK)
                {
                    pager.PageIndex = 0;
                    LoadUserList();
                }
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Form f = new frmUserInfo("", new string[] { "", "", "", "0" });
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                pager.PageIndex = 0;
                LoadUserList();
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvUserList.SelectedRows.Count > 0)
                {
                    string userName = dgvUserList.SelectedRows[0].Cells["Username"].Value.ToString();
                    if (userName.ToLower().Equals(Program.strUserName.ToLower()))
                        MessageBox.Show(UpdateUI.GetString("khongcodulieu"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                        if (MessageBox.Show(UpdateUI.GetString("bancochacchanxoa"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (_wcfUser.User_Delete(userName))
                            {
                                Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("xoathanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                                pager.PageIndex = 0;
                                LoadUserList();
                            }
                            else
                            {
                                MessageBox.Show(UpdateUI.GetString("xoakhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(UpdateUI.GetString("loi") + ":\n" + ex.Message + "\n" + UpdateUI.GetString("ghiloi"));
            }
        }

        private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
                btnEdit_Click(null, null);
        }

        private void frmUserList_Activated(object sender, EventArgs e)
        {
        }

        private void frmUserList_FormClosing(object sender, FormClosingEventArgs e)
        {
            _wcfUser.Close();
        }

        DataTable dtBranch; 
        private void cboRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            _BranchRegionCode = cboRegion.ComboBox.SelectedValue.ToString() != "0" ? cboRegion.ComboBox.SelectedValue.ToString() : "";
            //UISetting.LoadBranchByRegionCode(ref cboRegion, _BranchRegionCode);
            BranchItems = null;


            dtBranch = _wcfBranch.Branch_GetByRegionCode(_BranchRegionCode).Tables[0];
            DataRow dr = dtBranch.NewRow();
                    dr["Branch_CodeName"] = "---Chọn Đơn vị---";
                    dr["Branch_ID"] = 0;
                    dtBranch.Rows.InsertAt(dr, 0);

            cboBranch2.SuggestComboBoxControl.DisplayMember = "Branch_CodeName";
            cboBranch2.SuggestComboBoxControl.ValueMember = "Branch_ID";
            cboBranch2.SuggestComboBoxControl.DataSource = dtBranch;


            
            ////
            //cboBranch2.SuggestComboBoxControl.DataSource = cboBranch.ComboBox.DataSource;
            //cboBranch2.SuggestComboBoxControl.DisplayMember = cboBranch.ComboBox.DisplayMember;
            //cboBranch2.SuggestComboBoxControl.ValueMember = cboBranch.ComboBox.ValueMember;
            // then you have to set the PropertySelector like this:
            // then you have to set the PropertySelector like this:
            cboBranch2.SuggestComboBoxControl.PropertySelector = collection => collection.Cast<DataRowView>().Select(p => p["Branch_Name"].ToString());
            // filter rule can be customized: e.g. a StartsWith search:
            cboBranch2.SuggestComboBoxControl.FilterRule = (item, text) => item.ToLower().Contains(text.Trim().ToLower());
            // ordering rule can also be customized: e.g. order by the surname:
            cboBranch2.SuggestComboBoxControl.SuggestListOrderRule = s => s.Split(' ')[1];

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            string username = dgvUserList.SelectedRows.Count > 0 ? dgvUserList.SelectedRows[0].Cells["UserName"].Value.ToString() : "";
            frmUserAndBranch frm = new frmUserAndBranch(username);
            frm.ShowDialog();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Int32.TryParse(Convert.ToString(cboBranch2.SuggestComboBoxControl.SelectedValue), out _BranchID);
            pager.PageIndex = 0;
            LoadUserList();
        }

        string[] BranchItems;
        string sPreBranchKey = "";
        private void cboBranch_TextChanged(object sender, EventArgs e)
        {
            if (sender is ToolStripComboBox)
            {
                //string sText = (sender as ToolStripComboBox).Text;
                //if (sPreBranchKey != sText)
                //{
                //    cboBranch.ComboBox.DroppedDown = true;
                //    string sFilter = "Branch_Id > 0 AND Branch_Name LIKE '%" + sText + "%'";
                //    (cboBranch.ComboBox.DataSource as DataTable).DefaultView.RowFilter = sFilter;
                //    sPreBranchKey = sText;
                //}
            }
        }

        private void pager_PageIndex_Changed(int pageIndex)
        {
            LoadUserList();
        }
    }

    public static class EnumerableExtensionsEx
    {
        public static AutoCompleteStringCollection ToAutoCompleteStringCollection(
            this IEnumerable<string> enumerable)
        {
            if (enumerable == null) throw new ArgumentNullException("enumerable");
            var autoComplete = new AutoCompleteStringCollection();
            foreach (var item in enumerable) autoComplete.Add(item);
            return autoComplete;
        }
    }
}
